昨天我們已經寫出了第一篇測試 今天我們就要來依靠 Shoulda Matchers 來簡化以及優化我們的測試
group :test do
gem 'shoulda-matchers', '~> 5.0'
end
然後跑 bundle install
他也告訴你他幫你多了好幾種 matchers 在官方文件上都查得到
將以下 code 放到 spec/rails_helper.rb
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
在底下也有告訴你基礎運用
# RSpec
RSpec.describe MenuItem, type: :model do
describe 'associations' do
it { should belong_to(:category).class_name('MenuCategory') }
# 測試關聯性
end
describe 'validations' do
it { should validate_presence_of(:name) }
# 測試是否為必填
it { should validate_uniqueness_of(:name).scoped_to(:category_id) }
# 測試是否是唯一值
end
end
我們就來優化一下昨天寫的測試吧!
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
context 'name must be present' do
it { should validate_presence_of(:name) }
# 等同於
# subject.should validate_presence_of(:name)
# it { is_expected.to validate_presence_of(:name) }
end
end
end
這行就可以直接拿來測 name 是不是有限制要必填,剛剛寫了這麼多但 Shoulda Matchers 一行就幫你搞定!
我們可以試著把 validates :name, presence: true
拔掉跑一次測試不會過
$ rspec spec/models/user_spec.rb
F
Failures:
1) User validations name must be present is expected to validate that :name cannot be empty/falsy
Failure/Error: it { should validate_presence_of(:name) }
Expected User to validate that :name cannot be empty/falsy, but this
could not be proved.
After setting :name to ‹""›, the matcher expected the User to be
invalid, but it was valid instead.
# ./spec/models/user_spec.rb:6:in `block (4 levels) in <top (required)>'
Finished in 0.06186 seconds (files took 2.86 seconds to load)
1 example, 1 failure
再放回去測試就會通過摟!
$ rspec spec/models/user_spec.rb
.
Finished in 0.0644 seconds (files took 3.86 seconds to load)
1 example, 0 failures
Shoulda Matchers 最主要是拿來測試 model 關聯性以及驗證 可以節省很多 code,其實還有很多語法可以使用在這邊就不多贅述了官方文件寫的挺詳細的!
在官方也有提及這兩種是否有差別,答案是沒有。只是現在更流行使用expect
在 betterspec也有說到目前主流使用expect
明天先來介紹 before
、after
!再來講 let
、let!
、subject
!